<?php
include_once '../admin/assets/con_haparzo.php';
// Include sitemap generator
include_once 'sitemap_generator.php';

// Get blog_id from URL
$blog_id = isset($_GET['blog_id']) ? (int)$_GET['blog_id'] : 0;

// Query to fetch blog post details
// Query to fetch blog post details with cluster slug
$sql = "SELECT b.blog_id, b.title, b.meta_description, b.content, b.created_at, 
        b.cluster, c.slug AS cluster_slug, c.cluster_name,
        bi.image_path AS featured_image
        FROM blog b
        LEFT JOIN blog_images bi ON b.blog_id = bi.blog_id AND bi.featured = 1
        LEFT JOIN cluster c ON b.cluster = c.id  -- JOIN cluster table to get slug
        WHERE b.blog_id = $blog_id";

        

$result = $conn->query($sql);
if ($result && mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);

    // Extract data from the row
    $blog_title_THIS = htmlspecialchars($row['title']);
    $meta_description = !empty($row['meta_description']) ? htmlspecialchars($row['meta_description']) : '';
    $content = ($row['content']);
    $created_at = $row['created_at'];
    $featured_image = htmlspecialchars($row['featured_image']);
    // Get cluster slug from cluster table, default to 'general' if empty
$cluster = !empty($row['cluster_slug']) ? $row['cluster_slug'] : 'general';
$cluster_name_display = !empty($row['cluster_name']) ? $row['cluster_name'] : 'General';
    // Create a DateTime object from the string
    $dateTime = new DateTime($created_at);
    $formattedDate = $dateTime->format('F jS, Y');
       ////echo  $featured_image;
       //exit();
}

// Query to get category through blog_categories table
$category = 'uncategorized';
$category_folder = 'uncategorized';
$category_id = 0;

$category_sql = "SELECT c.category_id, c.name, c.`folder-name` as folder_name
                 FROM blog_categories bc
                 INNER JOIN categories c ON bc.category_id = c.category_id
                 WHERE bc.blog_id = $blog_id
                 LIMIT 1";
                 
$category_result = $conn->query($category_sql);
if ($category_result && mysqli_num_rows($category_result) > 0) {
    $category_row = mysqli_fetch_assoc($category_result);
    $category = htmlspecialchars($category_row['name']);
    $category_id = $category_row['category_id'];
    $category_folder = !empty($category_row['folder_name']) ? $category_row['folder_name'] : preg_replace('/[^A-Za-z0-9\-]/', '_', $category);
}

$Id_Blog = $blog_id;

// Sanitize cluster, category and blog title for folder names
$cluster_folder = preg_replace('/[^A-Za-z0-9\-]/', '_', $cluster);
$blog_slug = preg_replace('/[^A-Za-z0-9\-]/', '_', $blog_title_THIS);

// Create the nested folder structure
//$base_path = __DIR__ . '../blogs/';
$base_path = __DIR__ . '/../blogs/'; 
//$base_path =  '../blogs/';
$cluster_path = $base_path . $cluster_folder . '/';
$category_path = $cluster_path . $category_folder . '/';
$blog_folder = $category_path . $blog_slug . '-' . $Id_Blog . '/';

// Create cluster folder if it doesn't exist
if (!file_exists($cluster_path)) {
    if (!mkdir($cluster_path, 0777, true)) {
        die('Failed to create cluster folder...');
    }
}

// Create category folder if it doesn't exist
if (!file_exists($category_path)) {
    if (!mkdir($category_path, 0777, true)) {
        die('Failed to create category folder...');
    }
}

// Create blog folder if it doesn't exist
if (!file_exists($blog_folder)) {
    if (!mkdir($blog_folder, 0777, true)) {
        die('Failed to create blog folder...');
    }
}

$file_path = $blog_folder . "index.php";

// Start buffering output
ob_start();

// Prepare share URLs - update to new path structure
$home_link = 'http://localhost/mintnmiles';

$current_url = $home_link . 
               '/blogs/' . 
               rawurlencode($cluster_folder) . '/' . 
               rawurlencode($category_folder) . '/' . 
               rawurlencode($blog_slug . '-' . $Id_Blog) . '/';
$share_title = urlencode($blog_title_THIS);
$share_description = urlencode(!empty($meta_description) ? $meta_description : $blog_title_THIS);
$share_image = !empty($featured_image) ? urlencode('http://' . $_SERVER['HTTP_HOST'] . '/' . $featured_image) : '';
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="description" content="<?php echo !empty($meta_description) ? $meta_description : 'Read our latest blog post about ' . $blog_title_THIS; ?>">
    <meta name="keywords" content="blog, article, <?php echo $blog_title_THIS; ?>, Mint N Miles, digital products, online business">
    <meta name="author" content="Mint N Miles">
    
    <!-- Open Graph Meta Tags -->
    <meta property="og:url" content="<?php echo $current_url; ?>">
    <meta property="og:type" content="article">
    <meta property="og:title" content="<?php echo $blog_title_THIS; ?>">
    <meta property="og:description" content="<?php echo !empty($meta_description) ? $meta_description : $blog_title_THIS; ?>">
    <?php if (!empty($featured_image)): ?>
    <meta property="og:image" content="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/' . $featured_image; ?>">
    <meta property="og:image:width" content="1200">
    <meta property="og:image:height" content="630">
    <?php endif; ?>
    <meta property="article:published_time" content="<?php echo $created_at; ?>">
    <meta property="article:author" content="Mint N Miles">
    <meta property="og:site_name" content="Mint N Miles">
    
    <!-- Twitter Card Meta Tags -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?php echo $blog_title_THIS; ?>">
    <meta name="twitter:description" content="<?php echo !empty($meta_description) ? $meta_description : $blog_title_THIS; ?>">
    <?php if (!empty($featured_image)): ?>
    <meta name="twitter:image" content="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/' . $featured_image; ?>">
    <?php endif; ?>
    <meta name="twitter:creator" content="@mintnmiles">
    
    <!-- Canonical URL -->
    <link rel="canonical" href="<?php echo $current_url; ?>">
    
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Title -->
    <title><?php echo $blog_title_THIS; ?> - Mint N Miles Blog</title>

    <!-- Favicon -->
    <link rel="icon" href="../../../../img/core-img/favicon.ico">

    <!-- Core Stylesheet -->
    <link href="../../../../style.css" rel="stylesheet">

    <!-- Responsive CSS -->
    <link href="../../../../css/responsive/responsive.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    
    <script src="../../../../js/jquery/jquery-2.2.4.min.js"></script>
    
    <style>
        /* Like button styles */
        .post-favourite a {
            color: #666;
            text-decoration: none;
            transition: all 0.3s ease;
        }

        .post-favourite a:hover {
            color: #e74c3c;
        }

        .post-favourite .fa-heart {
            color: #e74c3c;
        }

        .post-favourite .fa-spin {
            animation: fa-spin 1s infinite linear;
        }
        
        .like-count {
            font-size: 0.9rem;
        }
        
        @keyframes fa-spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(359deg); }
        }

        .category-badge {
            background-color: #888d91ff;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            font-size: 0.775rem;
            margin-right: 0.5rem;
            display: inline-block;
            margin-bottom: 0.25rem;
        }

        .category-badge a {
            color: white !important;
            text-decoration: none;
        }

        .category-badge a:hover {
            color: #f8f9fa !important;
            text-decoration: none;
        }

        /* Cluster and Category Badges */
        .cluster-badge {
            background-color: #3498db;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            font-size: 0.775rem;
            margin-right: 0.5rem;
            display: inline-block;
            margin-bottom: 0.25rem;
        }

        .category-badge-alt {
            background-color: #2ecc71;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            font-size: 0.775rem;
            margin-right: 0.5rem;
            display: inline-block;
            margin-bottom: 0.25rem;
        }

        .tag-badge {
            background-color: #9b59b6;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            font-size: 0.775rem;
            margin-right: 0.5rem;
            display: inline-block;
            margin-bottom: 0.25rem;
        }

        .cluster-badge a,
        .category-badge-alt a,
        .tag-badge a {
            color: white !important;
            text-decoration: none;
        }

        .cluster-badge a:hover,
        .category-badge-alt a:hover,
        .tag-badge a:hover {
            color: #f8f9fa !important;
            text-decoration: none;
        }

        /* Enhanced Social Share Styles */
        .enhanced-share-section {
            border-top: 1px solid #e9ecef;
            padding-top: 30px;
            margin-top: 40px;
        }

        .share-widget {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            border-left: 4px solid #3498db;
        }

        .share-title {
            color: #2c3e50;
            font-weight: 600;
            font-size: 1.2rem;
            margin-bottom: 20px;
        }

        .share-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .share-btn {
            display: flex;
            align-items: center;
            padding: 10px 15px;
            border: none;
            border-radius: 6px;
            text-decoration: none;
            color: white;
            font-weight: 500;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .share-btn i {
            margin-right: 8px;
            font-size: 1.1rem;
        }

        .share-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            color: white;
            text-decoration: none;
        }

        /* Social Platform Colors */
        .facebook-btn { background: #3b5998; }
        .twitter-btn { background: #1da1f2; }
        .linkedin-btn { background: #0077b5; }
        .pinterest-btn { background: #bd081c; }
        .whatsapp-btn { background: #25d366; }
        .telegram-btn { background: #0088cc; }
        .copy-btn { background: #6c757d; }

        .facebook-btn:hover { background: #344e86; }
        .twitter-btn:hover { background: #1a91da; }
        .linkedin-btn:hover { background: #00669c; }
        .pinterest-btn:hover { background: #a50618; }
        .whatsapp-btn:hover { background: #20bd5a; }
        .telegram-btn:hover { background: #0077b3; }
        .copy-btn:hover { background: #5a6268; }

        /* Sidebar Share Button Hover Effects */
        .single-post-share-info a {
            transition: all 0.3s ease;
            border-radius: 4px;
            padding: 8px;
            display: block;
            margin-bottom: 10px;
        }

        .single-post-share-info a:hover {
            transform: scale(1.1);
            background: rgba(0,0,0,0.1);
        }

        .single-post-share-info .facebook:hover { color: #3b5998; }
        .single-post-share-info .twitter:hover { color: #1da1f2; }
        .single-post-share-info .linkedin:hover { color: #0077b5; }
        .single-post-share-info .pinterest:hover { color: #bd081c; }
        .single-post-share-info .whatsapp:hover { color: #25d366; }
        .single-post-share-info .email:hover { color: #d44638; }

        /* Responsive Design */
        @media (max-width: 768px) {
            .share-buttons {
                justify-content: center;
            }
            
            .share-btn {
                flex: 1;
                min-width: 120px;
                justify-content: center;
                margin-bottom: 10px;
            }
            
            .share-btn span {
                font-size: 0.9rem;
            }
            
            .single-post-share-info {
                text-align: center;
            }
            
            .single-post-share-info a {
                display: inline-block;
                margin: 5px;
            }
        }

        @media (max-width: 576px) {
            .share-btn {
                min-width: 100px;
                padding: 8px 12px;
            }
            
            .share-btn span {
                display: none;
            }
            
            .share-btn i {
                margin-right: 0;
            }
        }
    </style>
</head>

<body>
    <!-- Preloader Start -->
    <div id="preloader">
        <div class="mintnmiles-load"></div>
    </div>

    <!-- Background Pattern Switcher -->
    <div id="pattern-switcher">
        Bg Pattern
    </div>
    <div id="patter-close">
        <i class="fa fa-times" aria-hidden="true"></i>
    </div>

    <!-- Headers -->
    <div id="header3"></div>
    
    <div id="alert-container" class="container mt-3"></div>
    
    <!-- ****** Breadcumb Area Start ****** -->
    <div class="breadcumb-area" style="background-image: url(../../../../admin/<?php echo !empty($featured_image) ? $featured_image : '../img/default-image.jpg'; ?>);">
        <div class="container h-100">
            <div class="row h-100 align-items-center">
                <div class="col-12">
                    <div class="bradcumb-title text-center">
                        <h2>Blog</h2>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="breadcumb-nav">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="../../"><i class="fa fa-home" aria-hidden="true"></i> Home</a></li>
                            <li class="breadcrumb-item"><a href="../../blogs/">Blogs</a></li>
                            <?php if (!empty($cluster)): ?>
                            <li class="breadcrumb-item"><a href="../../blogs/<?php echo urlencode($cluster_folder); ?>/"><?php echo htmlspecialchars($cluster); ?></a></li>
                            <?php endif; ?>
                            <?php if (!empty($category) && $category != 'uncategorized'): ?>
                            <li class="breadcrumb-item"><a href="../../blogs/<?php echo urlencode($cluster_folder); ?>/<?php echo urlencode($category_folder); ?>/"><?php echo htmlspecialchars($category); ?></a></li>
                            <?php endif; ?>
                            <li class="breadcrumb-item active" aria-current="page"><?php echo $blog_title_THIS ?></li>
                        </ol>
                    </nav>
                </div>
            </div>
        </div>
    </div>
    <!-- ****** Breadcumb Area End ****** -->

    <!-- ****** Single Blog Area Start ****** -->
    <section class="single_blog_area section_padding_80">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-12 col-lg-8">
                    <div class="row no-gutters">

                        <!-- Single Post Share Info -->
                        <div class="col-2 col-sm-1">
                            <div class="single-post-share-info mt-100">
                                <!-- Facebook Share -->
                                <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($current_url); ?>&quote=<?php echo $share_title; ?>" 
                                   target="_blank" 
                                   rel="noopener noreferrer" 
                                   class="facebook" 
                                   title="Share on Facebook"
                                   onclick="openShareWindow(this.href); return false;">
                                    <i class="fab fa-facebook" aria-hidden="true"></i>
                                </a>
                                
                                <!-- Twitter Share -->
                                <a href="https://twitter.com/intent/tweet?url=<?php echo urlencode($current_url); ?>&text=<?php echo $share_title; ?>" 
                                   target="_blank" 
                                   rel="noopener noreferrer" 
                                   class="twitter" 
                                   title="Share on Twitter"
                                   onclick="openShareWindow(this.href); return false;">
                                    <i class="fab fa-twitter" aria-hidden="true"></i>
                                </a>
                                
                                <!-- LinkedIn Share -->
                                <a href="https://www.linkedin.com/sharing/share-offsite/?url=<?php echo urlencode($current_url); ?>" 
                                   target="_blank" 
                                   rel="noopener noreferrer" 
                                   class="linkedin" 
                                   title="Share on LinkedIn"
                                   onclick="openShareWindow(this.href); return false;">
                                    <i class="fab fa-linkedin" aria-hidden="true"></i>
                                </a>
                                
                                <!-- Pinterest Share -->
                                <a href="https://pinterest.com/pin/create/button/?url=<?php echo urlencode($current_url); ?>&media=<?php echo $share_image; ?>&description=<?php echo $share_title; ?>" 
                                   target="_blank" 
                                   rel="noopener noreferrer" 
                                   class="pinterest" 
                                   title="Share on Pinterest"
                                   onclick="openShareWindow(this.href); return false;">
                                    <i class="fab fa-pinterest" aria-hidden="true"></i>
                                </a>
                                
                                <!-- WhatsApp Share -->
                                <a href="https://api.whatsapp.com/send?text=<?php echo urlencode($blog_title_THIS . ' ' . $current_url); ?>" 
                                   target="_blank" 
                                   rel="noopener noreferrer" 
                                   class="whatsapp" 
                                   title="Share on WhatsApp"
                                   onclick="openShareWindow(this.href); return false;">
                                    <i class="fab fa-whatsapp" aria-hidden="true"></i>
                                </a>
                                
                                <!-- Email Share -->
                                <a href="mailto:?subject=<?php echo urlencode($blog_title_THIS); ?>&body=Check out this article: <?php echo urlencode($current_url); ?>" 
                                   class="email" 
                                   title="Share via Email">
                                    <i class="fas fa-envelope" aria-hidden="true"></i>
                                </a>
                            </div>
                        </div>

                        <!-- Single Post -->
                        <div class="col-10 col-sm-11">
                            <div class="single-post">
                                <!-- Post Thumb -->
                                <div class="post-thumb">
                                    <img src="../../../../admin/<?php echo !empty($featured_image) ? $featured_image : '../img/default-image.jpg'; ?>" alt="<?php echo $blog_title_THIS; ?>">
                                </div>
                                
                                <!-- Post Content -->
                                <div class="post-content">
                                    <div id="blog_parameter_tab"></div>
                                    
                                    <a href="#">
                                        <h2 class="post-headline"><?php echo $blog_title_THIS ?></h2>
                                    </a>
                                    
                                    <!-- Post Meta -->
                                    <div class="post-meta mt-3 mb-3">
                                        <span class="post-date">
                                            <i class="far fa-calendar me-1"></i>
                                            <?php echo $formattedDate; ?>
                                        </span>
                                    </div>
                                    
                                    <!-- Meta Description Display -->
                                    <?php if (!empty($meta_description)): ?>
                                    <div class="meta-description mt-2 mb-3">
                                        <p class="text-muted font-italic"><?php echo $meta_description; ?></p>
                                    </div>
                                    <?php endif; ?>

                                    <!-- Cluster and Category Display -->
                                    <div class="post-taxonomy mt-3 mb-3">
                                        <?php if (!empty($cluster)): ?>
                                        <span class="cluster-badge badge mr-1">
                                            <a href="../../blogs/<?php echo urlencode($cluster_folder); ?>/" style="color: white; text-decoration: none;">
                                                <i class="fas fa-folder me-1"></i><?php echo htmlspecialchars($cluster); ?>
                                            </a>
                                        </span>
                                        <?php endif; ?>
                                        
                                        <?php if (!empty($category) && $category != 'uncategorized'): ?>
                                        <span class="category-badge-alt badge mr-1">
                                            <a href="../../blogs/<?php echo urlencode($cluster_folder); ?>/<?php echo urlencode($category_folder); ?>/" style="color: white; text-decoration: none;">
                                                <i class="fas fa-tag me-1"></i><?php echo htmlspecialchars($category); ?>
                                            </a>
                                        </span>
                                        <?php endif; ?>
                                    </div>

                                    <!-- Tags Display -->
                                    <div class="post-tags mt-3 mb-3">
                                        <?php
                                        // Query to fetch tags for this blog post
                                        $tags_sql = "SELECT t.tag_id, t.tag_name 
                                                    FROM blog_tags bt 
                                                    INNER JOIN tags t ON bt.tag_id = t.tag_id 
                                                    WHERE bt.blog_id = $blog_id";
                                        
                                        $tags_result = $conn->query($tags_sql);
                                        
                                        if ($tags_result && mysqli_num_rows($tags_result) > 0) {
                                            echo '<div class="tags-list">';
                                            echo '<strong>Tags: </strong>';
                                            
                                            while ($tag_row = mysqli_fetch_assoc($tags_result)) {
                                                $tag_name = htmlspecialchars($tag_row['tag_name']);
                                                $tag_id = $tag_row['tag_id'];
                                                
                                                echo '<span class="tag-badge badge mr-1">';
                                                echo '<a href="../../../../tags/?tag_id=' . $tag_id . '" style="color: white; text-decoration: none;">';
                                                echo $tag_name;
                                                echo '</a>';
                                                echo '</span> ';
                                            }
                                            echo '</div>';
                                        }
                                        ?>
                                    </div>
                                    <!-- End Tags -->
                                    
                                    <div class="post-content-text">
                                        <?php echo $content ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Tags Area -->
                            <div class="tags-area mt-4">
                                <!-- Tags can be added here if needed -->
                            </div>

                            <!-- Enhanced Social Share Section -->
                            <div class="enhanced-share-section">
                                <div class="row">
                                    <div class="col-12">
                                        <div class="share-widget">
                                            <h5 class="share-title">
                                                <i class="fas fa-share-alt me-2"></i>Share This Article
                                            </h5>
                                            <div class="share-buttons">
                                                <!-- Facebook -->
                                                <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($current_url); ?>&quote=<?php echo $share_title; ?>" 
                                                   class="share-btn facebook-btn"
                                                   onclick="openShareWindow(this.href); return false;">
                                                    <i class="fab fa-facebook"></i>
                                                    <span>Facebook</span>
                                                </a>
                                                
                                                <!-- Twitter -->
                                                <a href="https://twitter.com/intent/tweet?url=<?php echo urlencode($current_url); ?>&text=<?php echo $share_title; ?>&via=mintnmiles" 
                                                   class="share-btn twitter-btn"
                                                   onclick="openShareWindow(this.href); return false;">
                                                    <i class="fab fa-twitter"></i>
                                                    <span>Twitter</span>
                                                </a>
                                                
                                                <!-- LinkedIn -->
                                                <a href="https://www.linkedin.com/sharing/share-offsite/?url=<?php echo urlencode($current_url); ?>" 
                                                   class="share-btn linkedin-btn"
                                                   onclick="openShareWindow(this.href); return false;">
                                                    <i class="fab fa-linkedin"></i>
                                                    <span>LinkedIn</span>
                                                </a>
                                                
                                                <!-- Pinterest -->
                                                <a href="https://pinterest.com/pin/create/button/?url=<?php echo urlencode($current_url); ?>&media=<?php echo $share_image; ?>&description=<?php echo $share_title; ?>" 
                                                   class="share-btn pinterest-btn"
                                                   onclick="openShareWindow(this.href); return false;">
                                                    <i class="fab fa-pinterest"></i>
                                                    <span>Pinterest</span>
                                                </a>
                                                
                                                <!-- WhatsApp -->
                                                <a href="https://api.whatsapp.com/send?text=<?php echo urlencode($blog_title_THIS . ' - ' . $current_url); ?>" 
                                                   class="share-btn whatsapp-btn"
                                                   onclick="openShareWindow(this.href); return false;">
                                                    <i class="fab fa-whatsapp"></i>
                                                    <span>WhatsApp</span>
                                                </a>
                                                
                                                <!-- Telegram -->
                                                <a href="https://t.me/share/url?url=<?php echo urlencode($current_url); ?>&text=<?php echo $share_title; ?>" 
                                                   class="share-btn telegram-btn"
                                                   onclick="openShareWindow(this.href); return false;">
                                                    <i class="fab fa-telegram"></i>
                                                    <span>Telegram</span>
                                                </a>
                                                
                                                <!-- Copy Link -->
                                                <button class="share-btn copy-btn" onclick="copyToClipboard('<?php echo $current_url; ?>')">
                                                    <i class="fas fa-link"></i>
                                                    <span>Copy Link</span>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Comment Button -->
                            <a href="#" class="btn contact-btn mt-4" data-bs-toggle="modal" data-bs-target="#CommentModal"> 
                                <i class="fas fa-comment me-2"></i>Create Comment
                            </a>

                            <!-- Comment Area -->
                            <div id="comment_list" class="mt-4"></div>
                        </div>
                    </div>
                </div>

                <script>
                function extractBlogPath(url) {
                    const regex = /\/blogs\/([^\/]+)\/([^\/]+)\/([^\/]+)\//;
                    const match = url.match(regex);
                    if (match) {
                        return {
                            cluster: match[1],
                            category: match[2],
                            blogSlug: match[3]
                        };
                    }
                    return null;
                }

                let currentUrl = window.location.href;
                let regex = /-(\d+)\//;
                let matches = currentUrl.match(regex);
                let page = 'blog_single';
                const blogPath = extractBlogPath(currentUrl);

                if (matches && matches[1]) {
                    let blogId = matches[1];
                    
                    // Get blog slug from the URL
                    const blogSlug = blogPath ? blogPath.blogSlug : '';
                   
                  
                   $.post("../../../../assets/header3_1.php", {
    val_blogSlug: blogSlug,
    val_blogId: blogId
}, function (header3) {
    $("#header3").html(header3);
});

                    
                    $.post("../../../../assets/footer3.php", {val_blogSlug: blogSlug, val_blogId: blogId}, function(footer3) {
                        $("#footer3").html(footer3);
                    });
                    
                    $.post("../../../../assets/popular_post.php", {}, function(popular_post) {
                        $("#popular_post").html(popular_post);
                    });
                    
                    $.post("../../../../assets/related_post.php", {val_blogId: blogId}, function(related_post) {
                        $("#related_post").html(related_post);
                    });
                    
                    $.post("../../../../assets/comment_list.php", {val_blogId: blogId}, function(comment_list) {
                        $("#comment_list").html(comment_list);
                    });
                    
                    $.post("../../../../assets/advert1.php", {val_blogSlug: blogSlug, val_blogId: blogId, page_val: page}, function(advert1) {
                        $("#advert1").html(advert1);
                    });
                    
                    $.post("../../../../assets/blog_parameter_tab.php", {val_blogSlug: blogSlug, val_blogId: blogId}, function(blog_parameter_tab) {
                        $("#blog_parameter_tab").html(blog_parameter_tab);
                    });

                    // Handle like button clicks
                    $(document).on('click', '.like-btn', function(e) {
                        e.preventDefault();
                        const blogId = $(this).data('blog-id');
                        const likeBtn = $(this);
                        const heartIcon = likeBtn.find('i');
                        const likeCount = likeBtn.find('.like-count');
                        
                        heartIcon.addClass('fa-spin');
                        
                        $.ajax({
                            url: "../../assets/handle_like.php",
                            method: "POST",
                            data: { blog_id: blogId },
                            dataType: "json",
                            success: function(response) {
                                if (response.success) {
                                    if (response.action === 'liked') {
                                        heartIcon.removeClass('fa-heart-o fa-spin').addClass('fa-heart');
                                    } else {
                                        heartIcon.removeClass('fa-heart fa-spin').addClass('fa-heart-o');
                                    }
                                    likeCount.text(response.new_count);
                                } else {
                                    alert(response.message || 'Error processing your like');
                                    heartIcon.removeClass('fa-spin');
                                }
                            },
                            error: function() {
                                alert('Network error - please try again');
                                heartIcon.removeClass('fa-spin');
                            }
                        });
                    });
                }

                // Social Share Functions
                function openShareWindow(url, width = 600, height = 400) {
                    const left = (screen.width - width) / 2;
                    const top = (screen.height - height) / 2;
                    window.open(url, 'share', `width=${width},height=${height},left=${left},top=${top}`);
                    
                    // Track social share
                    const platform = getPlatformFromUrl(url);
                    trackSocialShare(platform);
                }

                function getPlatformFromUrl(url) {
                    if (url.includes('facebook.com')) return 'facebook';
                    if (url.includes('twitter.com')) return 'twitter';
                    if (url.includes('linkedin.com')) return 'linkedin';
                    if (url.includes('pinterest.com')) return 'pinterest';
                    if (url.includes('whatsapp.com')) return 'whatsapp';
                    if (url.includes('telegram.me')) return 'telegram';
                    return 'other';
                }

                function trackSocialShare(platform) {
                    // You can integrate with Google Analytics here
                    console.log('Shared on:', platform);
                    
                    if (typeof gtag !== 'undefined') {
                        gtag('event', 'share', {
                            'method': platform,
                            'content_type': 'article',
                            'content_id': '<?php echo $blog_id; ?>'
                        });
                    }
                }

                function copyToClipboard(text) {
                    navigator.clipboard.writeText(text).then(function() {
                        showCopySuccess();
                    }, function(err) {
                        // Fallback for older browsers
                        const textArea = document.createElement('textarea');
                        textArea.value = text;
                        document.body.appendChild(textArea);
                        textArea.select();
                        document.execCommand('copy');
                        document.body.removeChild(textArea);
                        showCopySuccess();
                    });
                }

                function showCopySuccess() {
                    const alertContainer = document.getElementById('alert-container');
                    const alertDiv = document.createElement('div');
                    alertDiv.className = 'alert alert-success alert-dismissible fade show';
                    alertDiv.innerHTML = `
                        <i class="fas fa-check-circle me-2"></i>
                        Link copied to clipboard!
                        <button type="button" class="close" data-dismiss="alert">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    `;
                    alertContainer.appendChild(alertDiv);
                    
                    setTimeout(() => {
                        $(alertDiv).alert('close');
                    }, 3000);
                }
                </script>

                <!-- ****** Blog Sidebar ****** -->
                <div class="col-12 col-sm-8 col-md-6 col-lg-4">
                    <div class="blog-sidebar mt-5 mt-lg-0">
                       
                        <!-- Single Widget Area -->
                        <div class="single-widget-area popular-post-widget">
                            <div class="widget-title text-center">
                                <h6>Popular Post</h6>
                            </div>
                            <div id="popular_post"></div>
                        </div>
                        
                        <!-- Single Widget Area -->
                        <div class="single-widget-area popular-post-widget">
                            <div class="widget-title text-center">
                                <h6>Related Post</h6>
                            </div>
                            <div id="related_post"></div>
                        </div>

                        <!-- Single Widget Area -->
                        <div class="single-widget-area about-me-widget text-center">
                            <div class="widget-title">
                                <h6>About Me</h6>
                            </div>
                            <div class="about-me-widget-thumb">
                                <img src="../../img/about-img/1.jpg" alt="Mint N Miles">
                            </div>
                            <h4 class="font-shadow-into-light">Paul</h4>
                            <p>The mind behind Mint and Miles is a web designer, KDP publisher, mobile app developer, and trained electrical engineer with an MBA. Combining technical skills with creative insights, he shares practical tips for online success. Outside of work, he's a dedicated husband and father. Discover strategies and inspiration to boost your online earnings through his blog!</p>
                        </div>

                        <!-- Single Widget Area -->
                        <div class="single-widget-area subscribe_widget text-center">
                            <div class="widget-title">
                                <h6>Subscribe &amp; Follow</h6>
                            </div>
                            <div class="subscribe-link">
                                <a href="#"><i class="fab fa-facebook" aria-hidden="true"></i></a>
                                <a href="#"><i class="fab fa-twitter" aria-hidden="true"></i></a>
                                <a href="#"><i class="fab fa-instagram" aria-hidden="true"></i></a>
                                <a href="#"><i class="fab fa-pinterest" aria-hidden="true"></i></a>
                                <a href="#"><i class="fab fa-youtube" aria-hidden="true"></i></a>
                            </div>
                        </div>

                        <!-- Advert Area -->
                        <div id="advert1"></div>
                        
                        <!-- Single Widget Area -->
                        <div class="single-widget-area newsletter-widget">
                            <div class="widget-title text-center">
                                <h6>Newsletter</h6>
                            </div>
                            <p>Subscribe our newsletter for get notification about new updates, information discount, etc.</p>
                            <div class="newsletter-form">
                                <form action="#" method="post">
                                    <input type="email" name="newsletter-email" id="email" placeholder="Your email">
                                    <button type="submit"><i class="fas fa-paper-plane" aria-hidden="true"></i></button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!-- ****** Single Blog Area End ****** -->

    <!-- ****** Footer Area Start ****** -->
    <div id="footer3"></div>
    <!-- ****** Footer Menu Area End ****** -->

    <!-- jQuery -->
    <script src="../../../../js/jquery/jquery-2.2.4.min.js"></script>
    
    <!-- Popper js -->
    <script src="../../../../js/bootstrap/popper.min.js"></script>
    
    <!-- Bootstrap-4 js -->
    <script src="../../../../js/bootstrap/bootstrap.min.js"></script>
    
    <!-- All Plugins JS -->
    <script src="../../../../js/others/plugins.js"></script>
    
    <!-- Active JS -->
    <script src="../../../../js/active.js"></script>
    
    <script>
        $(document).ready(function(){
            $('.related-post-slider').owlCarousel({
                items: 3,
                loop: true,
                margin: 10,
                nav: true,
                dots: false,
                autoplay: true,
                autoplayTimeout: 3000,
                autoplayHoverPause: true,
                responsive: {
                    0: { items: 1 },
                    600: { items: 2 },
                    1000: { items: 3 }
                }
            });
        });
    </script>
</body>
</html>
<?php
// Get the contents of the output buffer
$html_content = ob_get_clean();

// Write the HTML content to the index.php file inside the created folder
file_put_contents($file_path, $html_content);

// Define the link to the dynamically generated file
$homelink = 'http://localhost/mintnmiles/';  // With trailing slash
$file_link = $homelink . 'blogs/' .  // NO leading slash
             urlencode($cluster_folder) . '/' . 
             urlencode($category_folder) . '/' . 
             urlencode($blog_slug . '-' . $Id_Blog) . '/';

// Update database with the file name and link
$folder_path = 'blogs/' . $cluster_folder . '/' . $category_folder . '/' . $blog_slug . '-' . $Id_Blog;
$query_file = $conn->query("UPDATE blog SET blog_folder_name='$folder_path', link='$file_link', published=1 WHERE blog_id='$Id_Blog'") or die(mysqli_error());

// Generate/Update sitemap
try {
    $sitemapGenerator = new SitemapGenerator($conn);
    
    // Check if this is a new blog or an update
    $check_sql = "SELECT published FROM blog WHERE blog_id = $Id_Blog";
    $check_result = $conn->query($check_sql);
    
    if ($check_result && mysqli_num_rows($check_result) > 0) {
        $blog_data = mysqli_fetch_assoc($check_result);
        
        if ($blog_data['published'] == 1) {
            // Blog was already published, update sitemap entry
            $sitemapGenerator->updateBlogEntry($Id_Blog);
        } else {
            // New blog publication, generate full sitemap
            $sitemapGenerator->generateSitemap();
        }
    }
} catch (Exception $e) {
    // Log error but don't stop the process
    error_log("Sitemap generation error: " . $e->getMessage());
}

header("Location: ../admin/view_blog_list.php");
exit;
?>